package com.victor.loading.newton;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;

/**
 * @author Yan
 *         create at 15/8/9
 */
public class CradleBall extends Component implements Component.DrawTask, Component.LayoutRefreshedListener {
    private int width;
    private int height;

    private Paint paint;

    private int loadingColor = Color.WHITE.getValue();

    public CradleBall(Context context) {
        super(context);
        initView(null);
    }

    public CradleBall(Context context, AttrSet attrs) {
        super(context, attrs);
        initView(attrs);
    }

    public CradleBall(Context context, AttrSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(attrs);
    }

    private void initView(AttrSet attrs) {
        setLayoutRefreshedListener(this::onRefreshed);
        new StyledAttributes(attrs);
        paint = new Paint();
        paint.setColor(new Color(loadingColor));
        paint.setStyle(Paint.Style.FILL_STYLE);
        paint.setAntiAlias(true);

        onRefreshed(this);
        addDrawTask(this::onDraw);
        invalidate();
    }

    @Override
    public void onRefreshed(Component component) {
        width = component.getWidth();
        height = component.getHeight();
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        canvas.drawCircle(width / 2, height / 2, width / 2, paint);
    }

    public void setLoadingColor(int color) {
        loadingColor = color;
        paint.setColor(new Color(color));
        invalidate();
    }

    public int getLoadingColor() {
        return loadingColor;
    }

    /**
     * Parse Style attributes
     */
    private class StyledAttributes {
        private final String colorValue = "cradle_ball_color";
        StyledAttributes(AttrSet attrs) {
            loadingColor = attrs.getAttr(colorValue).isPresent()
                    ? attrs.getAttr(colorValue).get().getIntegerValue() : Color.WHITE.getValue();
        }
    }
}
